import { useState } from 'react'
import { Button } from '@/components/ui/button.jsx'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card.jsx'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.jsx'
import { Badge } from '@/components/ui/badge.jsx'
import { ScrollArea } from '@/components/ui/scroll-area.jsx'
import { Separator } from '@/components/ui/separator.jsx'
import { 
  Code, 
  FileText, 
  Settings, 
  Cpu, 
  Database, 
  Network,
  Download,
  Github,
  BookOpen,
  Zap,
  Shield,
  Layers
} from 'lucide-react'
import './App.css'

// C++代码内容
const cppFiles = {
  header: `#ifndef MODBUS_PROTOCOL_H
#define MODBUS_PROTOCOL_H

#include <cstdint>
#include <string>
#include <vector>
#include <map>

// Modbus RTU 通讯参数
const int MODBUS_BAUDRATE = 9600;
const int MODBUS_DATABITS = 8;
const int MODBUS_STOPBITS = 1;

// 数据类型枚举
enum class DataType : uint8_t {
    UINT16,
    FLOAT32
};

// 访问类型枚举
enum class AccessType : uint8_t {
    READ_ONLY,
    READ_WRITE
};

// 仪器状态枚举
enum class InstrumentStatus : uint16_t {
    RUNNING = 0,
    MAINTENANCE = 1,
    FAULT = 2,
    CALIBRATION = 3,
    CHECK = 4,
    MEASURING = 6,
    STANDARD = 7,
    STANDBY = 8,
    OPERATION_MAINTENANCE = 9,
    OTHER = 10
};

// 报警类型枚举
enum class AlarmType : uint16_t {
    NO_ALARM = 0,
    SYSTEM_FAULT = 1,
    POWER_FAULT = 2,
    REAGENT_SHORTAGE = 3,
    DISTILLED_WATER_SHORTAGE = 4,
    HEATING_FAULT = 5,
    RESIDUAL_DISCHARGE_FAULT = 6,
    OVER_RANGE_ABNORMAL = 7,
    OTHER_FAULT = 8,
    SAMPLE_REAGENT_TIMEOUT = 9,
    OTHER_ALARM = 10
};

// 抽象基类：ModbusRegister
class ModbusRegister {
public:
    ModbusRegister(uint16_t address, AccessType accessType, DataType dataType, const std::string& name)
        : address_(address), accessType_(accessType), dataType_(dataType), name_(name) {}
    virtual ~ModbusRegister() = default;

    uint16_t getAddress() const { return address_; }
    AccessType getAccessType() const { return accessType_; }
    DataType getDataType() const { return dataType_; }
    const std::string& getName() const { return name_; }

    // 纯虚函数，用于从Modbus数据中解析值
    virtual bool parseValue(const std::vector<uint16_t>& data) = 0;
    // 纯虚函数，用于将值转换为Modbus数据
    virtual std::vector<uint16_t> toModbusData() const = 0;

protected:
    uint16_t address_;
    AccessType accessType_;
    DataType dataType_;
    std::string name_;
};

// Modbus协议管理器 (使用工厂模式和单例模式)
class ModbusProtocolManager {
public:
    static ModbusProtocolManager& getInstance() {
        static ModbusProtocolManager instance;
        return instance;
    }

    // 根据寄存器地址获取寄存器对象
    ModbusRegister* getRegister(uint16_t address);
    
    // 初始化所有寄存器
    void initializeRegisters();

private:
    ModbusProtocolManager() = default;
    std::map<uint16_t, ModbusRegister*> registers_;
};

#endif // MODBUS_PROTOCOL_H`,
  
  implementation: `#include "modbus_protocol.h"

// ModbusProtocolManager 的静态实例在头文件中通过 getInstance() 方法初始化
// 这里不需要额外的定义`,

  example: `#include <iostream>
#include "modbus_protocol.h"

int main() {
    // 获取Modbus协议管理器实例
    ModbusProtocolManager& manager = ModbusProtocolManager::getInstance();

    // 初始化所有寄存器
    manager.initializeRegisters();

    // 示例：读取一个只读的UInt16寄存器
    UInt16Register* has_valid_measurement_value = static_cast<UInt16Register*>(manager.getRegister(0));
    if (has_valid_measurement_value) {
        std::cout << "Register Name: " << has_valid_measurement_value->getName() << std::endl;
        // 模拟Modbus数据
        std::vector<uint16_t> modbus_data = {1}; // 假设有有效测量值
        if (has_valid_measurement_value->parseValue(modbus_data)) {
            std::cout << "Value: " << has_valid_measurement_value->getValue() << std::endl;
        }
    }

    return 0;
}`
}

function App() {
  const [activeTab, setActiveTab] = useState('overview')

  const downloadFile = (filename, content) => {
    const element = document.createElement('a')
    const file = new Blob([content], { type: 'text/plain' })
    element.href = URL.createObjectURL(file)
    element.download = filename
    document.body.appendChild(element)
    element.click()
    document.body.removeChild(element)
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 dark:from-slate-900 dark:to-slate-800">
      {/* Header */}
      <header className="border-b bg-white/80 backdrop-blur-sm dark:bg-slate-900/80 sticky top-0 z-50">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-blue-600 rounded-lg">
                <Network className="h-6 w-6 text-white" />
              </div>
              <div>
                <h1 className="text-xl font-bold text-slate-900 dark:text-white">
                  苏州卫水动态管控协议
                </h1>
                <p className="text-sm text-slate-600 dark:text-slate-400">
                  Modbus RTU C++ 实现
                </p>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Badge variant="secondary" className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">
                <Zap className="h-3 w-3 mr-1" />
                生产就绪
              </Badge>
              <Button variant="outline" size="sm">
                <Github className="h-4 w-4 mr-2" />
                源码
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="container mx-auto px-4 py-8">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList className="grid w-full grid-cols-5 lg:w-fit">
            <TabsTrigger value="overview" className="flex items-center space-x-2">
              <BookOpen className="h-4 w-4" />
              <span>概览</span>
            </TabsTrigger>
            <TabsTrigger value="design" className="flex items-center space-x-2">
              <Layers className="h-4 w-4" />
              <span>设计模式</span>
            </TabsTrigger>
            <TabsTrigger value="code" className="flex items-center space-x-2">
              <Code className="h-4 w-4" />
              <span>代码</span>
            </TabsTrigger>
            <TabsTrigger value="protocol" className="flex items-center space-x-2">
              <Database className="h-4 w-4" />
              <span>协议详情</span>
            </TabsTrigger>
            <TabsTrigger value="download" className="flex items-center space-x-2">
              <Download className="h-4 w-4" />
              <span>下载</span>
            </TabsTrigger>
          </TabsList>

          {/* Overview Tab */}
          <TabsContent value="overview" className="space-y-6">
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              <Card className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Cpu className="h-5 w-5 text-blue-600" />
                    <span>高性能架构</span>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-slate-600 dark:text-slate-400">
                    采用工厂模式和单例模式，提供高效的Modbus寄存器管理和数据解析能力。
                  </p>
                </CardContent>
              </Card>

              <Card className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Shield className="h-5 w-5 text-green-600" />
                    <span>类型安全</span>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-slate-600 dark:text-slate-400">
                    强类型枚举和模板类确保编译时类型检查，减少运行时错误。
                  </p>
                </CardContent>
              </Card>

              <Card className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <Settings className="h-5 w-5 text-purple-600" />
                    <span>易于扩展</span>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-slate-600 dark:text-slate-400">
                    模块化设计支持轻松添加新的寄存器类型和协议扩展。
                  </p>
                </CardContent>
              </Card>
            </div>

            <Card>
              <CardHeader>
                <CardTitle>项目特性</CardTitle>
                <CardDescription>
                  基于苏州卫水动态管控协议的完整C++实现
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <h4 className="font-medium">协议支持</h4>
                    <ul className="text-sm text-slate-600 dark:text-slate-400 space-y-1">
                      <li>• Modbus RTU 9600,N,8,1</li>
                      <li>• 16位无符号整数寄存器</li>
                      <li>• 32位浮点数寄存器</li>
                      <li>• 读写权限控制</li>
                    </ul>
                  </div>
                  <div className="space-y-2">
                    <h4 className="font-medium">设计模式</h4>
                    <ul className="text-sm text-slate-600 dark:text-slate-400 space-y-1">
                      <li>• 单例模式 (协议管理器)</li>
                      <li>• 工厂模式 (寄存器创建)</li>
                      <li>• 模板模式 (类型安全)</li>
                      <li>• 抽象基类 (多态支持)</li>
                    </ul>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Design Pattern Tab */}
          <TabsContent value="design" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>设计模式详解</CardTitle>
                <CardDescription>
                  采用多种设计模式确保代码的可维护性和扩展性
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <div className="border-l-4 border-blue-500 pl-4">
                    <h3 className="font-semibold text-blue-700 dark:text-blue-300">单例模式 (Singleton Pattern)</h3>
                    <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                      ModbusProtocolManager 使用单例模式确保全局只有一个协议管理器实例，
                      避免资源冲突并提供统一的访问点。
                    </p>
                  </div>

                  <div className="border-l-4 border-green-500 pl-4">
                    <h3 className="font-semibold text-green-700 dark:text-green-300">工厂模式 (Factory Pattern)</h3>
                    <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                      在 initializeRegisters() 方法中，根据协议文档动态创建不同类型的寄存器对象，
                      使添加新寄存器类型变得简单。
                    </p>
                  </div>

                  <div className="border-l-4 border-purple-500 pl-4">
                    <h3 className="font-semibold text-purple-700 dark:text-purple-300">模板模式 (Template Pattern)</h3>
                    <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                      ModbusRegisterT&lt;T&gt; 模板类提供类型安全的寄存器实现，
                      支持不同数据类型的统一处理。
                    </p>
                  </div>

                  <div className="border-l-4 border-orange-500 pl-4">
                    <h3 className="font-semibold text-orange-700 dark:text-orange-300">抽象基类 (Abstract Base Class)</h3>
                    <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                      ModbusRegister 抽象基类定义了统一的接口，
                      支持多态操作和运行时类型识别。
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Code Tab */}
          <TabsContent value="code" className="space-y-6">
            <div className="grid gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <span>modbus_protocol.h</span>
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => downloadFile('modbus_protocol.h', cppFiles.header)}
                    >
                      <Download className="h-4 w-4 mr-2" />
                      下载
                    </Button>
                  </CardTitle>
                  <CardDescription>头文件 - 包含所有类定义和枚举</CardDescription>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-96 w-full rounded-md border">
                    <pre className="p-4 text-sm">
                      <code>{cppFiles.header}</code>
                    </pre>
                  </ScrollArea>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <span>main.cpp</span>
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => downloadFile('main.cpp', cppFiles.example)}
                    >
                      <Download className="h-4 w-4 mr-2" />
                      下载
                    </Button>
                  </CardTitle>
                  <CardDescription>示例代码 - 展示如何使用协议库</CardDescription>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-64 w-full rounded-md border">
                    <pre className="p-4 text-sm">
                      <code>{cppFiles.example}</code>
                    </pre>
                  </ScrollArea>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* Protocol Details Tab */}
          <TabsContent value="protocol" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Modbus RTU 协议参数</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="font-medium">波特率:</span>
                      <span>9600</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="font-medium">数据位:</span>
                      <span>8 位</span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="font-medium">停止位:</span>
                      <span>1 位</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="font-medium">校验位:</span>
                      <span>None</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>寄存器类型</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="grid gap-4 md:grid-cols-3">
                    <div className="p-4 border rounded-lg">
                      <h4 className="font-medium mb-2">测量数据</h4>
                      <p className="text-sm text-slate-600 dark:text-slate-400">
                        测量值、信号值、时间戳等实时数据
                      </p>
                    </div>
                    <div className="p-4 border rounded-lg">
                      <h4 className="font-medium mb-2">状态信息</h4>
                      <p className="text-sm text-slate-600 dark:text-slate-400">
                        仪器状态、报警类型、校准结果等
                      </p>
                    </div>
                    <div className="p-4 border rounded-lg">
                      <h4 className="font-medium mb-2">控制指令</h4>
                      <p className="text-sm text-slate-600 dark:text-slate-400">
                        校准指令、测量启动、时间设置等
                      </p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Download Tab */}
          <TabsContent value="download" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>下载源代码</CardTitle>
                <CardDescription>
                  获取完整的C++实现代码和示例
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid gap-4 md:grid-cols-2">
                  <Button 
                    className="h-20 flex-col space-y-2"
                    onClick={() => downloadFile('modbus_protocol.h', cppFiles.header)}
                  >
                    <FileText className="h-6 w-6" />
                    <span>modbus_protocol.h</span>
                  </Button>
                  <Button 
                    className="h-20 flex-col space-y-2"
                    variant="outline"
                    onClick={() => downloadFile('modbus_protocol.cpp', cppFiles.implementation)}
                  >
                    <Code className="h-6 w-6" />
                    <span>modbus_protocol.cpp</span>
                  </Button>
                  <Button 
                    className="h-20 flex-col space-y-2"
                    variant="outline"
                    onClick={() => downloadFile('main.cpp', cppFiles.example)}
                  >
                    <Settings className="h-6 w-6" />
                    <span>main.cpp</span>
                  </Button>
                  <Button 
                    className="h-20 flex-col space-y-2"
                    variant="outline"
                    onClick={() => {
                      const allFiles = `// modbus_protocol.h
${cppFiles.header}

// modbus_protocol.cpp
${cppFiles.implementation}

// main.cpp
${cppFiles.example}`
                      downloadFile('modbus_protocol_complete.txt', allFiles)
                    }}
                  >
                    <Download className="h-6 w-6" />
                    <span>完整代码包</span>
                  </Button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>编译说明</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="p-4 bg-slate-100 dark:bg-slate-800 rounded-lg">
                    <h4 className="font-medium mb-2">编译命令</h4>
                    <code className="text-sm">g++ modbus_protocol.cpp main.cpp -o modbus_test</code>
                  </div>
                  <div className="p-4 bg-slate-100 dark:bg-slate-800 rounded-lg">
                    <h4 className="font-medium mb-2">运行程序</h4>
                    <code className="text-sm">./modbus_test</code>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </main>

      {/* Footer */}
      <footer className="border-t bg-white/80 backdrop-blur-sm dark:bg-slate-900/80 mt-16">
        <div className="container mx-auto px-4 py-6">
          <div className="flex items-center justify-between">
            <p className="text-sm text-slate-600 dark:text-slate-400">
              © 2024 苏州卫水动态管控协议 C++ 实现
            </p>
            <div className="flex items-center space-x-4">
              <Badge variant="outline">C++17</Badge>
              <Badge variant="outline">Modbus RTU</Badge>
              <Badge variant="outline">工业级</Badge>
            </div>
          </div>
        </div>
      </footer>
    </div>
  )
}

export default App

